#include"myepoll.h"
#include"error.h"
#include<unistd.h>
#include<string.h>
#include"channel.h"
#include<iostream>

#define maxEventNum 1000

myepoll::myepoll(/* args */)
{
    epfd = epoll_create1(0);
    printError(epfd == -1,"高并发文件描述符");
    epollEvent = new epoll_event[maxEventNum];
    bzero(epollEvent,sizeof(epollEvent)*maxEventNum);
}

myepoll::~myepoll()
{
    //关闭文件描述符 删除数据防止发生内存泄漏
    if(epfd !=-1){
        close(epfd);
        epfd = -1;
    }
    delete[] epollEvent;
}


std::vector<MyChannel *> myepoll::poll(int timeout)
{
    std::vector<MyChannel*> activeEvent;
    int nfds;
    do {
        nfds = epoll_wait(epfd, epollEvent, maxEventNum, timeout);
        if (nfds == -1 && errno == EINTR) {
            // 被信号中断，继续等待
            continue;
        }
        printError(nfds == -1,"找到事件");
    } while (nfds == -1 && errno == EINTR);

    for(int i = 0; i < nfds; i++){
        MyChannel *ch = (MyChannel*)epollEvent[i].data.ptr;
        ch->setRevents(epollEvent[i].events);
        activeEvent.emplace_back(ch);
    }

    return activeEvent;
}

void myepoll::updateChannel(MyChannel *ch) {  
    int fd = ch->getFd();
    struct epoll_event ev;
    bzero(&ev, sizeof(ev));

    if(fd<0) return;

    ev.data.ptr = ch;  // 正确：使用 ptr 存储 Channel 指针
    ev.events = ch->getEvents();

    if (!ch->getInEpoll()) {
        printError(epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) == -1, "epoll add error");
        ch->setInEpoll();
    } else {
        printError(epoll_ctl(epfd, EPOLL_CTL_MOD, fd, &ev) == -1, "epoll modify error");
    }
}
